//
//  VOLAppDelegate.m
//  Volver
//
//  Created by administrator on 14-9-15.
//  Copyright (c) 2014年 vol. All rights reserved.
//

#import "VOLAppDelegate.h"

#import "HTTPDefine.h"
#import "common.h"

#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "FMDatabase.h"
#import "JSONKit.h"

#import "User.h"
#import "House.h"
#import "VOLChatUser.h"

#define kDBPath @"volTalk.sqlite"


@implementation VOLAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    [NSThread sleepForTimeInterval:1.5];
    self.xmppsteam = [[XMPPStream alloc]init];
    self.rosters = [NSMutableArray array];
    self.xmpprosterdatastorge = [[XMPPRosterCoreDataStorage alloc]init];
    
    //因为打开后要进入精选界面，所以设置isRefresh为6，进入界面时刷新，
    self.isRefresh = 6;
    
    //设置初始状态为未登录
    self.isLogin = NO;
    
    //初始化currentUser对象
    self.currentUser = [[User alloc] init];
    
#pragma mark 检测网络连接情况
    reach = [Reachability reachabilityWithHostName:@"www.apple.com"];
    if ([reach currentReachabilityStatus] == NotReachable) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络异常" message:@"请检查网络设置!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alert show];
        return YES;
    }
    //设置初始状态为不是自动登录
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    self.isAutologin = [[userDefaults stringForKey:@"isAutoLogin"] intValue];
    NSLog(@"%d",self.isAutologin);
    
    
    if (self.isAutologin) {
        
        //读取本地保存的用户名和密码
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSString *userPhone = [userDefaults stringForKey:@"userPhone"];
        NSString *userPassword = [userDefaults stringForKey:@"userPassword"];
        
        
        if (userPhone == nil || userPassword == nil) {
            NSLog(@"没有用户登录过");
            return YES;
        }
        [self userLoginUserPhone:userPhone userPassword:userPassword];
    }
    
    
    [self createDB];
    
    self.offlinemessagedic = [[NSMutableDictionary alloc]init];
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark - User相关的方法
#pragma mark 将返回的用户信息赋给一个user的对应属性

-(void)initUser:(User *)user withUserDic:(NSDictionary *)userDic{
    user.userID = [[userDic objectForKey:@"user_id"] intValue];
    user.userName = [userDic objectForKey:@"user_name"];
    user.userPhone = [userDic objectForKey:@"user_phone"];
    user.userPassword = [userDic objectForKey:@"user_password"];
    user.userMail = [userDic objectForKey:@"user_mail"];
    user.userSex = [userDic objectForKey:@"user_sex"];
    
    NSString *tempBirth = [userDic objectForKey:@"user_birth"];
    if ((NSNull *)tempBirth != [NSNull null]) {
        user.userBirth = [[userDic objectForKey:@"user_birth"] doubleValue];
    }
    
    user.userHead = [userDic objectForKey:@"user_head"];
    
    NSString *tempRegisterTime = [userDic objectForKey:@"user_register_time"];
    if ((NSNull *)tempRegisterTime != [NSNull null]) {
        user.userRegisterTime = [[userDic objectForKey:@"user_register_time"] doubleValue];
    }
}


#pragma mark 用户登录
-(int)userLoginUserPhone:(NSString *)userPhone userPassword:(NSString *)userPassword{
    
    self.pwd = [MD5 md5HexDigest:userPassword];
    
    //发送POST请求判断是否是有效的用户
    NSString *urlstr = [NSString stringWithFormat:@"%@user/login",kHTTPHome];
    NSURL *url = [NSURL URLWithString:urlstr];
    //创建同步请求对象
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    
    //    NSString *userPhone = @"18801548987";
    //    NSString *userPassword = @"bwj123";
    
    //设置数据
    [request setPostValue:userPhone forKey:@"userPhone"];
    [request setPostValue:[MD5 md5HexDigest:userPassword] forKey:@"userPassword"];
    
    //设置请求方式
    [request setRequestMethod:@"POST"];
    
    
    //发送同步请求
    [request startSynchronous];
    
    if (request.error != nil) {
        NSLog(@"请求失败");
        return -2;
    }
    
    JSONDecoder *jd = [[JSONDecoder alloc] init];
    
    NSData *data = [request responseData];
    
    //若没有数据返回，直接结束函数
    if (data == nil) {
        NSLog(@"user---data为空");
        return -3;
    }
    
    NSDictionary *dic = [jd objectWithData:data];
    int status = [[dic objectForKey:@"status"] intValue];
    
    if (status == 1) {
        NSArray *array = [dic objectForKey:@"user"];
        NSDictionary *userDic = array[0];
        
        [self initUser:self.currentUser withUserDic:userDic];
        self.isLogin = YES;
        
        //连接聊天的服务器
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self contactChatServer:userPhone];
        });
        
    }else{
        NSLog(@"登录失败");
    }
    
    return status;
}

#pragma mark 加载头像图片
-(void)loadHeadImage:(NSString *)imageName userID:(int)userID headImageView:(UIImageView *)headImageView imagePath:(NSString *)imagePath{
    
    //开启新线程加载图片
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //组装image的url
        NSString *urlstr = [NSString stringWithFormat:@"%@%d/%@",kUserHeadHome,userID,imageName];
        NSURL *url = [NSURL URLWithString:urlstr];
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *image = [UIImage imageWithData:data];
        if (image !=nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                headImageView.image = image;
                //本地保存图片
                [data writeToFile:imagePath atomically:YES];
            });
        }
        else{
            NSLog(@"没有图片");
        }
    });
    
}

#pragma mark 连接聊天的服务器
-(void)contactChatServer:(NSString *)userPhone{
    
    self.rosters = [[NSMutableArray alloc]init];//初始化聊天用户数组
    
    //连接聊天的服务器
    self.xmppsteam = [[XMPPStream alloc]init]; //初始化xmppstream
    [self.xmppsteam addDelegate:self delegateQueue:dispatch_get_main_queue()]; //设置代理
    XMPPJID *jid = [XMPPJID jidWithString:[NSString stringWithFormat:@"%@%@",userPhone,kXMPPLocal]];//连接服务去账号名
    self.username = [NSString stringWithFormat:@"%@%@",userPhone,kXMPPLocal] ;
    [self.xmppsteam setMyJID:jid];
    [self.xmppsteam setHostName:kXMPPID]; //设置服务器的地址
    
    //连接服务器，如果失败，则打印连接失败
    NSError *error =  nil ;
    if (![self.xmppsteam connectWithTimeout:5 error:&error]) {
        NSLog(@"连接xmpp服务器失败");
    }
    
    self.xmpproster = [[XMPPRoster alloc]initWithRosterStorage:self.xmpprosterdatastorge];
    self.xmpproster.autoAcceptKnownPresenceSubscriptionRequests = YES ; //自动获取好友状态
    self.xmpproster.autoFetchRoster = YES ; //自动获取花名册
    [self.xmpproster activate:self.xmppsteam];
    [self.xmpproster addDelegate:self delegateQueue:dispatch_get_main_queue()]; //添加代理
}

#pragma mark - XMPP

#pragma mark xmppstream连接服务器成功
-(void)xmppStreamDidConnect:(XMPPStream *)sender{
    
    NSError *error = nil ;
    
    //验证该账号的密码
    if (![self.xmppsteam authenticateWithPassword:self.pwd error:&error]){
        NSLog(@"%@",[[error userInfo] description]);
    }
    
}

#pragma mark xmpp密码验证成功
-(void)xmppStreamDidAuthenticate:(XMPPStream *)sender{
    
    NSLog(@"密码验证成功");
    
    //向服务器发送自己的状态为在线
    XMPPPresence *presence = [XMPPPresence presenceWithType:@"available"];
    [self.xmppsteam sendElement:presence];
    
}

#pragma mark 密码验证失败则打印
-(void) xmppStream:(XMPPStream *)sender didNotAuthenticate:(DDXMLElement *)error{
    
    NSLog(@"验证密码失败");
    
}

#pragma mark 查询好友列表
- (void)queryRoster {
    
    NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:@"jabber:iq:roster"];
    NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"];
    XMPPJID *myJID = self.xmppsteam.myJID;
    [iq addAttributeWithName:@"from" stringValue:myJID.description];
    [iq addAttributeWithName:@"to" stringValue:myJID.domain];
    [iq addAttributeWithName:@"id" stringValue:self.username];
    [iq addAttributeWithName:@"type" stringValue:@"get"];
    [iq addChild:query];
    [self.xmppsteam sendElement:iq];
}


#pragma mark- 修改用户的密码
-(void) updatepassword:(NSString *)name :(NSString *)pwd{
    
    XMPPJID *myJID = self.xmppsteam.myJID;
    NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"];
    [iq addAttributeWithName:@"to" stringValue:myJID.domain];
    [iq addAttributeWithName:@"id" stringValue:self.username];
    [iq addAttributeWithName:@"type" stringValue:@"set"];
    
    NSXMLElement *queryElement = [NSXMLElement elementWithName:@"query" xmlns:@"jabber:iq:register"];
    [iq addChild:queryElement];
    
    NSXMLElement *username = [NSXMLElement elementWithName:@"username"];
    [username setStringValue:name];
    NSXMLElement *password = [NSXMLElement elementWithName:@"password"];
    [password  setStringValue:pwd];
    
    [queryElement addChild:username];
    [queryElement addChild:password];
    
    [self.xmppsteam sendElement:iq];
    NSLog(@"%@",iq.description);
}


#pragma mark 返回好友列表，将好友的名字加入数组
- (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq {
    
    if ([@"result" isEqualToString:iq.type])
    {
        
        NSXMLElement *query = iq.childElement;
        
        if ([@"query" isEqualToString:query.name])
        {
            
            NSArray *items = [query children];
            for (NSXMLElement *item in items)
            {
                NSString *jid = [item attributeStringValueForName:@"jid"]; //获取好友的jid
                
                if (jid.length >13)
                {
                    //将该用加入好友数组
                    VOLChatUser *user = [[VOLChatUser alloc]init];
                    user.name = jid ;
                    NSLog(@"%@",jid);
                    [self.rosters addObject:user];
                    [self getUseHead:user];
                }
            }
        }
    }
    
    
    return YES ;
}

#pragma mark 接受新消息的代理方法
-(void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message{
    NSLog(@"收到一条消息");
    if ([[message elementForName:@"body"] stringValue] != nil) {
        
        NSString *messages = [[message elementForName:@"body"] stringValue];
        
        //获取消息的发送者
        NSString *prencefrom =  [[message attributeForName:@"from"]stringValue];
        NSArray *array = [prencefrom componentsSeparatedByString:@"/"];
        NSString *from = [array objectAtIndex:0];
        
        //获取该消息的接受者
        NSString *prenceto = [[message attributeForName:@"to"]stringValue];
        NSArray *toarray = [prenceto componentsSeparatedByString:@"/"];
        NSString *to = [toarray objectAtIndex:0];
        
        //获取当前时间
        NSString *messagetime = [self getnowtime];
        
        //将该消息插入sqllite数据库
        [self insertmessage:from withmessageto:to withmessagecontent:messages withmessage:messagetime];
        
        //如果该消息为发送到聊天页面的用户，则通知聊天页面刷新数据
        [[NSNotificationCenter defaultCenter]postNotificationName:from object:messages];
        
        //如果用户数组里没有用户的名字等于发消息来的名字，则将该发来消息的用户加入数组
        if (from.length >13) {
            
            
            int flag = 0 ;
            for ( VOLChatUser *ur in self.rosters)
            {
                
                if ([ur.name isEqualToString:from])
                {
                    flag ++ ;
                    
                }
                
            }
            
            if (flag == 0 )
            {
                VOLChatUser *user = [[VOLChatUser alloc]init];
                if (user.name.length >13)
                {
                    
                    user.name = from ;
                    user.pearence = @"unavailable" ;
                    [self.rosters addObject:user];
                    [self getUseHead:user];
                }
            }
            
            
            //将该用户的离线消息加1
            for (VOLChatUser *user in self.rosters) {
                NSLog(@"name------%@",user.name);
                if ([user.name isEqualToString:from ]) {
                    user.offlinemessage ++ ;
                    NSString *filename = [kGetDocumentsPath stringByAppendingPathComponent:@"offlinemessage.plist"];
                    NSArray *array = [NSArray arrayWithObjects:user.name,[ NSNumber numberWithInteger:user.offlinemessage ] ,nil];
                    [self.offlinemessagedic setObject:array forKey:user.name];
                    if ([self.offlinemessagedic writeToFile:filename atomically:YES]) {
                        NSLog(@"写入成功了");
                        NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithContentsOfFile:filename];
                        NSLog(@"dddd------%@",dic);
                    }
                    
                    
                }
            }
            
        }
        
    }
    
    //通知好友列表页面更新好友的离线消息数量，刷新数据
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ChangeNameNotice" object:@"errr"];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"setofflinemessage" object:nil];
    
}

#pragma mark 他人发来好友请求时，默认为自动接受
-(void)xmppRoster:(XMPPRoster *)sender didReceivePresenceSubscriptionRequest:(XMPPPresence *)presence{
    
    //取得好友状态
    NSString *presenceType = [NSString stringWithFormat:@"%@", [presence type]]; //online/offline
    //请求的用户
    NSString *presenceFromUser =[NSString stringWithFormat:@"%@", [[presence from] user]];
    NSLog(@"presenceType:%@",presenceType);
    
    NSLog(@"presence2:%@  sender2:%@",presence,sender);
    
    XMPPJID *jid = [XMPPJID jidWithString:[NSString stringWithFormat:@"%@%@",presenceFromUser,kXMPPLocal]];
    
    NSLog(@"他人发来好友请求时---------%@",presenceFromUser);
    
    //如果别人对自己发来好友请求时，则接收该请求
    [self.xmpproster acceptPresenceSubscriptionRequestFrom:jid andAddToRoster:YES];
    
    //将发送好友请求的用户加入到用户数组
    int flag = 0 ;
    for ( VOLChatUser *ur in self.rosters)
    {
        
        if ([ur.name isEqualToString:[NSString stringWithFormat:@"%@%@",presenceFromUser,kXMPPLocal]]) {
            flag ++ ;
            
        }
        
    }
    
    if (flag == 0 )
    {
        VOLChatUser *user = [[VOLChatUser alloc]init];
        user.name = [NSString stringWithFormat:@"%@%@",presenceFromUser,kXMPPLocal] ;
        if (user.name.length >14) {
            user.pearence = @"unavailable" ;
            [self.rosters addObject:user];
            [self getUseHead:user];
        }
        
    }
}

#pragma mark 收到好友上下线状态
- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence {
    NSLog(@"获取好友状态");
    //取得好友状态
    NSString *presenceType = [NSString stringWithFormat:@"%@", [presence type]]; //
    NSString *presenceFromUser =[NSString stringWithFormat:@"%@", [[presence from] user]];
    NSString *nr = [NSString stringWithFormat:@"%@%@",presenceFromUser,kXMPPLocal];
    
    
    //这里再次加好友
    if ([presenceType isEqualToString:@"subscribed"]) {
        XMPPJID *jid = [XMPPJID jidWithString:[NSString stringWithFormat:@"%@",[presence from]]];
        NSLog(@"这里再次加好友-----%@",[presence from]);
        [self.xmpproster acceptPresenceSubscriptionRequestFrom:jid andAddToRoster:YES];
    }
    
    
    if (![presenceFromUser isEqualToString:[[sender myJID] user]])
    {
        //如果该用户的状态为在线时，将他的chatuser类的属性设为在线
        if ([presenceType isEqualToString:@"available"])
        {
            
            NSString *nr = [NSString stringWithFormat:@"%@%@",presenceFromUser,kXMPPLocal];
            for (VOLChatUser *ur in self.rosters)
            {
                if ([ur.name isEqualToString: nr])
                {
                    ur.pearence = @"available";
                }
            }
        }
        
        else if ([presenceType isEqualToString:@"unavailable"])
        {
            for (VOLChatUser *ur in self.rosters)
            {
                if ([ur.name isEqualToString: nr])
                {
                    ur.pearence = @"unavailable";
                    NSLog(@"%@",nr);
                }
            }
        }
        
    }
    
    
    //获取状态后，通过消息中心告诉好友列表界面，刷新数据
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ChangeNameNotice" object:@"errr"];
    
    
}

#pragma mark 发送消息成功后，将该消息插入数据库
-(void)xmppStream:(XMPPStream *)sender didSendMessage:(XMPPMessage *)message{
    
    NSLog(@"发送消息成功了");
    if ([[message elementForName:@"body"] stringValue] != nil)
    {
        
        //获取消息的内容
        NSString *messages = [[message elementForName:@"body"] stringValue];
        
        //获取自己的账号名
        NSString *prencefrom = self.xmppsteam.myJID.description ;
        NSArray *array = [prencefrom componentsSeparatedByString:@"/"];
        NSString *from = [array objectAtIndex:0];
        
        //获取消息接受者的账号名
        NSString *prenceto = [[message attributeForName:@"to"]stringValue];
        NSArray *toarray = [prenceto componentsSeparatedByString:@"/"];
        NSString *to = [toarray objectAtIndex:0];
        
        //获取当前的时间
        NSString *messagetime = [self getnowtime];
        
        //将该消息插入到数据库
        [self insertmessage:from withmessageto:to withmessagecontent:messages withmessage:messagetime];
    }
    
}


#pragma mark 创建数据库存储的路径
-(NSString *)getDBPath
{
    NSFileManager *manager = [NSFileManager defaultManager];
    
    NSString * messagepath =  [NSString stringWithFormat:@"%@message",kGetDocumentsPath];
    
    //如果该路径不存在，则创建该路径
    if (![manager fileExistsAtPath:messagepath])
    {
        
        [manager createDirectoryAtPath:messagepath withIntermediateDirectories:YES attributes:nil error:nil];
        
    }
    
    
    return [NSString stringWithFormat:@"%@/%@",messagepath,kDBPath];
    
}


#pragma mark 创建数据库（第一次运行时执行）
-(void)createDB
{
    //获取文件沙盒存储路径
    NSString *path = [self getDBPath];
    
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:path]) {
        
        //不存在时自动创建数据库文件
        FMDatabase * db = [FMDatabase databaseWithPath:[self getDBPath]];
        
        //创建数据库表talk
        if ([db open]) {
            
            NSString * sql = @"CREATE TABLE 'talk' ('id' INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL , 'messagefrom' VARCHAR NOT NULL , 'messageto' VARCHAR NOT NULL , 'messagecontent' VARCHAR,'messagetime' VARCHAR NOT NULL)";
            
            BOOL res = [db executeUpdate:sql];
            if (res) {
                
                //创建数据库成功
                NSLog(@"数据库创建成功");
                [db close]; //关闭数据库
            }
        }
        
    }
    
}

#pragma mark 获取当前时间，并将它格式化为字符串
-(NSString *) getnowtime{
    
    NSDate *chatdate = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy年MM月dd日 H时K分ss秒"];
    NSString *messagetime = [formatter stringFromDate:chatdate];
    return messagetime ;
}



#pragma mark 数据库插入数据
-(void)insertmessage:(NSString *)messaggfrom withmessageto:(NSString *)messageto withmessagecontent:(NSString *) messagecontent withmessage:(NSString *) messagetime{
    
    FMDatabase *db = [FMDatabase databaseWithPath:[self getDBPath]];
    
    //插入数据
    if ([db open]) {
        NSString *sql = @"insert into  talk (messagefrom,messageto, messagecontent,messagetime) values (?,?,?,?)" ;
        
        BOOL succceed =   [db executeUpdate:sql,messaggfrom,messageto,messagecontent,messagetime];
        
        if (succceed) {
            
            [db close]; //插入成功后，关闭数据库
            
        }
        
    }
    
}

#pragma mark 通过用户的号码来获取用户的id号和头像名
-(void)getUseHead:(VOLChatUser *)user
{
    
    //通过用户的账号名裁剪出手机号
    NSString *name = user.name ;
    NSArray *phonearray = [name componentsSeparatedByString:@"@"];
    NSString *phonenumbers= [phonearray objectAtIndex:0];
    
    
    //接口请求信息
    NSString *urlString = [NSString stringWithFormat:@"%@user/getHeadByUserPhone?userPhone=%@",kHTTPHome,phonenumbers];
    NSURL *url = [NSURL URLWithString:urlString];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    request.delegate = self ;
    [request setRequestMethod:@"GET"];
    [request startSynchronous];
    NSData *data = [request responseData];
    
    
    //如果返回成功，则将获得的信息赋值给user的属性
    if (data) {
        JSONDecoder *json = [[JSONDecoder alloc]init];
        NSDictionary *dic = [json objectWithData:data];
        int status = [[dic objectForKey:@"status"] intValue];
        if (status == 1) {
            
            NSArray *idhead = [dic objectForKey:@"idAndHead"];
            NSDictionary *k = [idhead objectAtIndex:0];
            NSString *headname = [k objectForKey:@"user_head"];
            NSString *userid = [k objectForKey:@"user_id"];
            NSString *volname = [k objectForKey:@"user_name"];
            user.headname = headname ;
            NSLog(@"iiiii----%@",headname);
            user.userid = userid ;
            user.volname = volname ;
            
        }
        
        
    }
    
}


@end
